package com.exampl.health.service.impl;

import com.exampl.health.dao.UserMapper;
import com.exampl.health.entity.User;
import com.exampl.health.exception.LoginFailedException;
import com.exampl.health.exception.UserExistException;
import com.exampl.health.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 用户服务实现类
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(String username, String password) throws LoginFailedException {
        // 参数验证
        if (username == null || username.trim().isEmpty()) {
            throw new LoginFailedException("用户名不能为空");
        }

        if (password == null || password.trim().isEmpty()) {
            throw new LoginFailedException("密码不能为空");
        }

        // 查询用户
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            throw new LoginFailedException("用户名不存在");
        }

        // 验证密码
        if (!user.getPassword().equals(password)) {
            throw new LoginFailedException("密码错误");
        }

        // 返回用户信息（不包含密码）
        user.setPassword(null);
        return user;
    }

    @Override
    public User register(User user) throws UserExistException {
        // 参数验证
        if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }

        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            throw new IllegalArgumentException("密码不能为空");
        }

        if (user.getEmail() == null || user.getEmail().trim().isEmpty()) {
            throw new IllegalArgumentException("邮箱不能为空");
        }

        // 检查用户名是否已存在
        if (isUsernameExist(user.getUsername())) {
            throw new UserExistException("用户名已存在");
        }

        // 检查邮箱是否已存在
        if (isEmailExist(user.getEmail())) {
            throw new UserExistException("邮箱已被注册");
        }

        // 设置默认头像（如果未提供）
        if (user.getAvatar() == null || user.getAvatar().isEmpty()) {
            user.setAvatar("/static/images/default-avatar.png");
        }

        // 设置创建时间
        user.setCreateTime(new Date());

        // 保存用户
        int result = userMapper.insert(user);
        if (result > 0) {
            // 返回用户信息（不包含密码）
            user.setPassword(null);
            return user;
        } else {
            throw new RuntimeException("注册失败，请稍后重试");
        }
    }

    @Override
    public User getUserById(Integer userId) {

        return userMapper.selectById(userId);
    }

    @Override
    public boolean isUsernameExist(String username) {

        return userMapper.selectByUsername(username) != null;
    }

    @Override
    public boolean isEmailExist(String email) {

        return userMapper.selectByEmail(email) != null;
    }
    @Override
    public boolean updateUserWithoutPassword(User user) {
        // 只更新用户名、邮箱和头像，不更新密码
        int result = userMapper.updateUserWithoutPassword(user);
        return result > 0;
    }

    @Override
    public boolean isEmailExists(String email, Integer excludeUserId) {
        User user = userMapper.selectByEmail(email);
        // 如果找到了用户，且不是排除的用户，则返回true
        return user != null && !user.getUserId().equals(excludeUserId);
    }

    @Override
    public boolean updateAvatar(Integer userId, String avatarPath) {
        User user = new User();
        user.setUserId(userId);
        user.setAvatar(avatarPath);
        int result = userMapper.updateAvatar(userId, avatarPath);
        return result > 0;
    }
}